<template>
  <main>
    <div>
      <div v-if="pending">
        Pending...
      </div>
      <div v-else>
        <h1>{{ $t('download') }}</h1>
        <p>Edit :{{ file }}</p>

        <UiForm v-if="!pending" :model="File" :entity="file">
          <template #form.input="{model, entity: file}">

            <UiInputText field="name" v-model="file.name" type="text" :rules="rules.nameRules" />
            <UiInputEnum field="status" v-model="file.status" enum="file_status" />

            <v-btn @click="cancel" class="ma-5">Annuler</v-btn>
            <v-btn @click="save" class="ma-5">Enregistrer</v-btn>
            <v-btn @click="deleteAndGoBack" class="ma-5">Supprimer</v-btn>
            <v-btn @click="refresh" class="ma-5">Refresh</v-btn>
            <v-btn @click="goBack" class="ma-5">Retour</v-btn>
            <v-btn to="/poc/display" class="ma-5">Détails</v-btn>
          </template>
        </UiForm>

        <v-btn to="/poc">Retour</v-btn>
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
import {useEntityManager} from "~/composables/data/useEntityManager";
import {ref, Ref} from "@vue/reactivity";
import File from "~/models/Core/File";
import {useEntityFetch} from "~/composables/data/useEntityFetch";
import {useI18n} from "vue-i18n";

const route = useRoute()

const id: Ref<number> = ref(parseInt(route.params.id as string))

const { em }= useEntityManager()

const { fetch } = useEntityFetch()

const { data: file, pending, refresh } = fetch(File, id.value)

// Get file from store
// const file: ComputedRef<File> = computed( () => {
//   return em.find(File, id.value)
// })

// Update store when form is changed
// const onFileChange = () => {
//   console.log(file.value)
//   em.save(File, file.value)
// }

const i18n = useI18n()
const rules = {
  nameRules: [
    (nameValue: string) => !!nameValue || i18n.t('required'),
    (nameValue: string) => (nameValue || '').length <= 128 || i18n.t('name_length_rule'),
    (nameValue: string) => (nameValue || '').length >= 2 || i18n.t('name_length_rule'),
  ]
}

const save = async () => {
  if (file.value === null) {
    throw new Error('File not found')
  }
  await em.persist(File, file.value)
}

const cancel = async () => {
  if (file.value === null) {
    throw new Error('File not found')
  }
  if (em.isNewInstance(File, id.value)) {
    await em.delete(File, file.value)
  } else {
    em.reset(File, file.value)
  }
}

const deleteItem = async () => {
  if (file.value === null) {
    throw new Error('File not found')
  }
  await em.delete(File, file.value)
}

const goBack = () => {
  navigateTo('/poc')
}

const saveAndGoBack = async () => {
  await save()
  goBack()
}

const cancelAndGoBack = async () => {
  await cancel()
  goBack()
}

const deleteAndGoBack = async () => {
  await deleteItem()
  goBack()
}
</script>

<style>
</style>
